package util

import (
	"math/big"
	"strings"
)

var (
	base9Alphabet = "012356789" // 9进制字母表，不包含数字4
)

// ConvertToExternalID 将10进制的内部ID转换成9进制的外部ID
func ConvertToExternalID(internalID int64) string {
	if internalID == 0 {
		return string(base9Alphabet[0])
	}

	var result strings.Builder
	base := big.NewInt(9)
	zero := big.NewInt(0)
	_ = big.NewInt(10)

	internalBigInt := big.NewInt(internalID)

	for internalBigInt.Cmp(zero) != 0 {
		// 取余数
		remainder := new(big.Int)
		internalBigInt.DivMod(internalBigInt, base, remainder)

		// 获取对应的9进制字符
		charIndex := remainder.Int64()
		result.WriteByte(base9Alphabet[charIndex])
	}

	// 反转字符串得到最终结果
	resultStr := result.String()
	return reverseString(resultStr)
}

// reverseString 反转字符串
func reverseString(s string) string {
	var result strings.Builder
	for i := len(s) - 1; i >= 0; i-- {
		result.WriteByte(s[i])
	}
	return result.String()
}

//func main() {
//	internalID := int64(123456)
//	externalID := ConvertToExternalID(internalID)
//	fmt.Printf("Internal ID: %d, External ID: %s\n", internalID, externalID)
//}
